package picture
import (
	"qiniupkg.com/api.v7/kodo"
	"qiniupkg.com/api.v7/conf"
	"qiniupkg.com/api.v7/kodocli"
	"fmt"
	"encoding/json"
	"io/ioutil"
	"io"
	"../env"
)
var QiniuConf = config{}
var configPathPreFix = "qiniu/qiniuConfig-"
var configPathSuffix = ".json"

type PutRet struct {
	Hash         string `json:"hash"`
	PersistentId string `json:"persistentId"`
	Key          string `json:"key"`
}
type config struct  {
	AccessKey string `json:"access_key"`
	SecretKey string `json:"secret_key"`
	Bucket string `json:"bucket"`
	Domain string `json:"domain"`
}

func UpLoad(fileRead io.Reader ,fileSize int64, key string) (ret PutRet,err error)  {
	// 初始化AK，SK
	conf.ACCESS_KEY = QiniuConf.AccessKey
	conf.SECRET_KEY = QiniuConf.SecretKey

	// 创建一个Client
	c := kodo.New(0, nil)
	// 设置上传的策略
	policy := &kodo.PutPolicy{
		Scope: QiniuConf.Bucket + ":" + key,
		// 设置Token过期时间
		Expires: 3600,
	}
	// 生成一个上传token

	token := c.MakeUptoken(policy)

	// 构建一个uploader
	zone := 0
	uploader := kodocli.NewUploader(zone, nil)
	ret = PutRet{}
	err = uploader.Put(nil,&ret,token, key,fileRead, fileSize,nil)
	// 打印返回的信息
	fmt.Println(ret)
	// 打印出错信息
	if err != nil {
		fmt.Println("io.Put failed:", err)
		return
	}
	return
}
func init() {
	b,err  := ioutil.ReadFile(env.EvnConfig.Cp+configPathPreFix+env.EvnConfig.Active+ configPathSuffix)
	if err !=nil {
		panic(err)
	}
	err = json.Unmarshal(b,&QiniuConf)
	fmt.Println("qiniu:",QiniuConf)
	if err != nil {
		panic(err)
	}
}